#include "TcpSever.hh"
#include "Protocol.hh"
#include <memory>

using namespace tom_tcpSever;
using namespace tom_protocol;

void usage(const string &proc)
{
    std::cout << "\nUsage: " << proc << " port\n";
}
void debug(int sock)
{
    cout << "我是测试服务,得到的sock:" << sock << endl;
}
static Response calculate(const Request &req)
{
    Response resp(0, 0);
    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;
        break;
    case '*':
        resp._result = req._x * req._y;
        break;
    case '/':
        if (0 == req._y)
            resp._code = 1;
        else
            resp._result = req._x / req._y;
        break;
    case '%':
        if (0 == req._y)
            resp._code = 2;
        else
            resp._result = req._x % req._y;
        break;
    default:
        resp._code = 3;
        break;
    }
    return resp;
}
void calculator(int sock)
{
    while (1)
    {
        string str = Recv(sock);
        Request req;
        req.Deserialize(str);
        Response resp = calculate(req);
        string respString = resp.Serialize();
        Send(sock, respString);
    }
}
// ./CalSever 8080
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        usage(argv[0]);
        exit(1);
    }
    unique_ptr<TcpServer> server(new TcpServer(atoi(argv[1])));
    // server->BindHandler(debug);
    server->BindHandler(calculator);
    server->Start();
}
